package com.example.kotlincoroutine

import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.supervisorScope
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import org.junit.Test
import java.lang.IllegalArgumentException
import kotlin.system.measureTimeMillis

class CoroutineTest04 {

    //把函数变成协程到方式用runBlocking
    @Test
    fun `test deal with timeout`() = runBlocking<Unit> {
        //指定执行时间，超时则出现异常 Timed out waiting for 1300 ms
        withTimeout(1300) {
            repeat(1000) { i ->
                println("job sleeping")
                delay(500L)
            }
        }
    }

    @Test
    fun `test deal with timeout return null`() = runBlocking<Unit> {
        //指定执行时间，超时则出现异常 Timed out waiting for 1300 ms
        val result = withTimeoutOrNull(1300) {
            repeat(1000) { i ->
                println("job sleeping")
                delay(500L)
            }
        } ?: "jack Null"
        println("result is $result")
    }
}